package com.deductive.web.disposition.wq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deductive.common.config.RuoYiConfig;
import com.deductive.common.core.controller.BaseController;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import com.deductive.common.utils.DateUtils;
import com.deductive.common.utils.encrypt.MD5Util;
import com.deductive.domain.sys.SysFiles;
import com.deductive.domain.wq.DispositionWqFajh;
import com.deductive.service.sys.SysFilesService;
import com.deductive.service.wq.DispositionWqFajhService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;



/**
 * 方案计划类.
 *
 * @author yexiaolong
 * @version 1.0
 * @since 2025/8/29
 */
@RestController
@RequestMapping("/Plan")
@Api(tags = "WQ-方案计划管理")
public class PlanController extends BaseController {

    @Resource
    private DispositionWqFajhService dispositionWqFajhService;

    @Resource
    private SysFilesService sysFilesService;

    @GetMapping("/list")
    @ApiOperation("方案计划列表")
    public TableDataInfo list(DispositionWqFajh data) {
        startPage();
        LambdaQueryWrapper<DispositionWqFajh> eq = new LambdaQueryWrapper<>();
        eq.like(data.getName()!=null,DispositionWqFajh::getName,data.getName());
        eq.orderByDesc(DispositionWqFajh::getCreateTime);
        List<DispositionWqFajh> list = dispositionWqFajhService.list(eq);
        return getDataTable(list);
    }

    @PutMapping("/update")
    @ApiOperation("方案计划修改")
    public AjaxResult update(@RequestBody DispositionWqFajh data) {
        try
        {
            data.setUpdateTime(DateUtils.getNowDate());
            return AjaxResult.success(dispositionWqFajhService.updateById(data));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage(),false);
        }
    }

    @PostMapping("/insert")
    @ApiOperation("方案计划新增")
    public AjaxResult insert(@RequestBody DispositionWqFajh data) {
        try
        {
            data.setCreateTime(DateUtils.getNowDate());
            return AjaxResult.success(dispositionWqFajhService.save(data));
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage(),false);
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        for (Long id : idList) {
            DispositionWqFajh plan= dispositionWqFajhService.getById(id);
            List<Long> fileIds = Arrays.stream(plan.getFileIds().split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            sysFilesService.removeByIds(fileIds);
        }
        sysFilesService.removeByIds(idList);
        return AjaxResult.success(dispositionWqFajhService.removeByIds(idList));
    }

    @PostMapping("/{id}/files/upload")
    @ApiOperation("上传文件并绑定到想定")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult uploadAndBind(@ApiParam(value = "想定ID", required = true, example = "1") @PathVariable("id") Long id,
                                    @ApiParam(value = "上传文件", required = true) @RequestPart("file") MultipartFile file,
                                    @ApiParam(value = "父目录ID，可选") @RequestParam(value = "parentId", required = false) Long parentId) {

        DispositionWqFajh plan = dispositionWqFajhService.getById(id);
        if (plan == null) {
            return error("想定不存在");
        }
        if (file == null || file.isEmpty()) {
            return error("上传文件不能为空");
        }
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                return error("文件名不能为空");
            }
            String extension = "";
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex > 0) {
                extension = originalFilename.substring(lastDotIndex + 1).toLowerCase();
            }

            String storageName = UUID.randomUUID().toString().replace("-", "");
            if (!extension.isEmpty()) {
                storageName += "." + extension;
            }

            String baseDir = RuoYiConfig.getFilePath();
            String datePath = LocalDate.now().toString();
            String uploadDir = baseDir + "/" + datePath;
            Path dir = Paths.get(uploadDir);
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            }

            String fullPath = uploadDir + "/" + storageName;
            Path targetPath = Paths.get(fullPath);
            Files.copy(file.getInputStream(), targetPath);

            String md5Hash = MD5Util.calculateMD5(file.getBytes());

            SysFiles sysFiles = new SysFiles();
            sysFiles.setFileName(originalFilename);
            sysFiles.setStorageName(storageName);
            sysFiles.setFilePath("/profile/files/" + datePath + "/" + storageName);
            sysFiles.setFileSize(file.getSize());
            sysFiles.setMimeType(file.getContentType());
            sysFiles.setExtension(extension);
            sysFiles.setMd5Hash(md5Hash);
            sysFiles.setUploadTime(new Date());
            sysFiles.setLastModified(new Date());
            sysFiles.setVersion(1);
            sysFiles.setParentId(parentId);
            sysFiles.setIsDirectory(false);
            sysFiles.setStatus(1);

            boolean saved = sysFilesService.save(sysFiles);
            if (!saved) {
                Files.deleteIfExists(targetPath);
                return error("文件保存失败");
            }

            // 绑定ID
            List<Long> newIds = new java.util.ArrayList<>();
            newIds.add(sysFiles.getId());
            Set<Long> merged = new LinkedHashSet<>();
            if (StringUtils.isNotBlank(plan.getFileIds())) {
                merged.addAll(Arrays.stream(plan.getFileIds().split(","))
                        .filter(StringUtils::isNotBlank)
                        .map(Long::valueOf)
                        .collect(Collectors.toList()));
            }
            merged.addAll(newIds);
            plan.setFileIds(merged.stream().map(String::valueOf).collect(Collectors.joining(",")));
            plan.setUpdateTime(DateUtils.getNowDate());
            boolean ok = dispositionWqFajhService.updateById(plan);
            if (!ok) {
                // 回滚文件
                sysFilesService.removeById(sysFiles.getId());
                Files.deleteIfExists(targetPath);
                return error("绑定失败");
            }
            return success(sysFiles).put("msg", "上传并绑定成功");
        } catch (IOException e) {
            return error("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            return error("系统错误：" + e.getMessage());
        }
    }

}
